package com.haohan.cloud.framework.constant;

import com.haohan.cloud.framework.entity.BaseStatus;
import com.haohan.cloud.framework.exception.NotInitException;
import com.haohan.cloud.framework.utils.CoreLogUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

public class RespStatusUtil{


	public static class UtilInit{
		private boolean init = false;
		private Class<? extends RespStatus> respStatus = null;

		public Class<? extends RespStatus> getRespStatus() {
			return respStatus;
		}
		public void setRespStatus(Class<? extends RespStatus> respStatus) {
			this.respStatus = respStatus;
			if(null != this.respStatus){
				init = true;
			}
		}
		public boolean isInit() {
			return init;
		}


	}

	public static class RespBaseStatus implements Serializable{
		private static final long serialVersionUID = 2121175337578582868L;

		private BaseStatus value = null;

		private String name = null;

		public RespBaseStatus() {
		}

		public RespBaseStatus(String name,BaseStatus value) {
			super();
			this.value = value;
			this.name = name;
		}

		public BaseStatus getValue() {
			return value;
		}

		public void setValue(BaseStatus value) {
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}


	}

    private static final ConcurrentHashMap<Integer,RespBaseStatus> STATUS_MAP = new ConcurrentHashMap<>();

    private static UtilInit utilInit = new UtilInit();

    public static void utilInit(Class<? extends RespStatus> respStatus){
    	utilInit.setRespStatus(respStatus);
    	defaultInitStatusMap(utilInit.getRespStatus());
    }

    public static void initStatusMap(){
    	if(!utilInit.isInit()){
    		throw new NotInitException("RespStatusUtil not set Class<? extends RespStatus> respStatus");
    	}

    }

    private static final <T extends RespStatus> void defaultInitStatusMap(Class<T> clazz){
    	Field[] fields = clazz.getFields();
    	for (Field field : fields) {
			try {
				Object o = field.get(null);
				if(o instanceof BaseStatus){
					BaseStatus bs = (BaseStatus)o;
					STATUS_MAP.put(bs.getCode(), new RespBaseStatus(field.getName(), bs));
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				CoreLogUtils.error("RespStatus.initStatusMap", e);
			}
		}
    }

    public static String nameOf(Integer code){
    	initStatusMap();
    	RespBaseStatus rbs = STATUS_MAP.get(code);
    	return null == rbs ? null : rbs.getName();
    }

    public static BaseStatus valueOf(Integer code){
    	initStatusMap();
    	RespBaseStatus rbs = STATUS_MAP.get(code);
    	return null == rbs ? null : rbs.getValue();
    }

}
